package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private UserService userService;


    @RequestMapping("/getMenuByUserName")
    public Result getMenuByUserName(String username){
        //根据用户名获取到对应的数据
        User user = userService.findByUserName(username);
        //获取到对应的角色信息
        Set<Role> roles = user.getRoles();
        if (roles != null && roles.size() > 0){
            for (Role role : roles) {
                //遍历角色集合
                LinkedHashSet<Menu> menus = role.getMenus();

                //创建一个集合
                LinkedHashSet<Map> menuList = new LinkedHashSet<>();
                for (Menu menu : menus) {
                    //创建一个map集合进行数据的封装操作
                    Map<String,Object> mainMap = new HashMap<>();
                    mainMap.put("path",menu.getPath());
                    mainMap.put("title",menu.getName());
                    mainMap.put("icon",menu.getIcon());

                    List<Menu> children = menu.getChildren();
                    if (children == null){
                        //如果没有相关子菜单
                        mainMap.put("children",children);
                    }

                    //创建一个新的List集合进行封装处理
                    List<Map> list = new ArrayList<>();
                    for (Menu child : children) {
                        //创建一个map集合封装处理二级菜单数据
                        Map map = new HashMap();
                        map.put("path",child.getPath());
                        map.put("title",child.getName());
                        map.put("linkUrl",child.getLinkUrl());
                        map.put("children",child.getChildren());
                        list.add(map);
                    }

                    mainMap.put("children",list);

                    menuList.add(mainMap);
                }

                return new Result(true, MessageConstant.GET_MENU_SUCCESS,menuList);
            }
        }
        return new Result(false,MessageConstant.GET_MENU_FAIL);
    }
}
